const fs = window.require("fs");
const { dialog } = window.require("electron").remote;

export default function uploadImage(
  state: {},
  {
    jud,
    fn,
    that,
  }: { jud: boolean; fn: Function; that: { __filePath: string } }
) {
  let imgBufferList: { blob: string; src: string }[] = [];
  let path;

  //选择图片
  path = dialog.showOpenDialogSync({
    filters: [{ name: "Images", extensions: ["jpg", "png", "gif", "jpeg"] }],
    properties: jud ? ["multiSelections"] : [], //判断是不是多选
  });

  if (path) {
    //图片复制到指定文件夹下
    path.forEach((item) => {
      try {
        let data = fs.readFileSync(item);
        let dirname = `${
          that.__filePath
        }/developPageImage/${new Date().getTime()}.${
          item
            .split("\\")
            .reverse()[0]
            .split(".")[1]
        }`;
        fs.writeFileSync(dirname, data);
        imgBufferList.push({
          blob: URL.createObjectURL(new Blob([data])),
          src: dirname,
        });
      } catch (error) {
        console.error(error);
        return fn([], error);
      }
    });

    return fn(imgBufferList);
  }

  return fn([]);
}
